<template>
  <el-drawer v-model="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false"
             :close-on-press-escape="false" size="900px">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef"
             :label-width="$i18n.locale === 'en-US' ? '120px' : '100px'">
      <el-form-item label="投票主题：" prop="theme">
        <el-input v-model="dataForm.theme" placeholder="请输入投票主题"></el-input>
      </el-form-item>
      <el-form-item label="截止时间：" prop="endTime">
        <el-date-picker
          v-model="dataForm.endTime"
          type="datetime"
          :disabled-date="disabledDate"
          format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择截止时间"
        />
      </el-form-item>
      <el-form-item label="投票类型：" prop="voteType">
        <el-switch v-model="dataForm.voteType" active-text="多选" inactive-text="单选" :active-value="1"
                   :inactive-value="0"/>
      </el-form-item>
      <el-button style="margin-bottom: 14px" type="primary" @click="addANS">添加选项</el-button>
      <el-form-item v-for="(item,index) in dataForm.voteOptionList" :label="'选项'+(index+1)+'：'" :key="index+'_key'">
        <div style="width: 100%;display: flex;align-items: center">
          <el-input v-model="item.optionName" placeholder="请输入选项内容"></el-input>
          <div style="width: 120px;text-align: center">
            <el-tooltip
              class="box-item"
              effect="dark"
              content="删除该选项"
              placement="top"
            >
              <el-button type="danger" @click="delectAns(index)" :icon="Delete" circle/>
            </el-tooltip>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle">发布</el-button>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import {reactive, ref} from "vue";
import baseService from "@/service/baseService";
import {useI18n} from "vue-i18n";
import {ElMessage} from "element-plus";
import {Delete} from '@element-plus/icons-vue';

const {t} = useI18n();
const emit = defineEmits(["refreshDataList"]);

const disabledDate = (time: any) => {
  return time.getTime() <= Date.now();
}

const visible = ref(false);
const dataFormRef = ref();

const dataForm = reactive({
  id: "",
  theme: "",
  endTime: "",
  voteOptionList: [],
  voteType: 0 // 题目类型(0:单选 1:多选)
}) as any;

const addANS = () => {
  dataForm.voteOptionList.push({
    optionName: ""
  })
}

const delectAns = (ind: number) => {
  dataForm.voteOptionList.splice(ind, 1);
}

const rules = ref({
  theme: [{required: true, message: t("validate.required"), trigger: "blur"}],
  endTime: [{required: true, message: t("validate.required"), trigger: "change"}]
});

const init = (id: number) => {
  visible.value = true;
  dataForm.id = "";
  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }
  if (id) {
    getInfo(id);
  }

};

// 获取信息
const getInfo = (id: number) => {
  baseService.get(`/clc/clcvote/${id}`).then((res) => {
    Object.assign(dataForm, res.data);
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    if (dataForm.voteOptionList.length === 0) {
      ElMessage.warning({
        message: "最少要有一个选项",
        duration: 2000
      });
      return
    }
    (!dataForm.id ? baseService.post : baseService.put)("/clc/clcvote", dataForm).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>
